package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Component
public class CacheUtil {
    
    private final StringRedisTemplate stringRedisTemplate;

    public CacheUtil(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    private static final ExecutorService CACHE_REBULID_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 1. 将任意Java对象序列化成json字符串并存储在string类型的key，并设置TTL时间
     */
    public void set(String key, Object value, Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time, unit);
    }

    /**
     * 将任意Java对象转化为json字符串并存贮在string类型的key中，并设定逻辑过期时间，用来对应缓存击穿
     */
    public void setKeyLuoJi(String key, Object value, Long time, TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));
    }

    public <R,ID> R getPassThrough(
            String keyPrefix, ID id, String lockPrefix,
            Class<R> type, Function<ID, R> dbFallBack,
            Long null_key_ttl,Long time, TimeUnit timeUnit){
        // 对要查询的信息进行字符串拼接
        String key = keyPrefix + id;
        // 从redis缓存中查询数据
        String json = stringRedisTemplate.opsForValue().get(key);
        // 对查询出来的结果进行判空操作，非空则直接进行返回
        if (StrUtil.isNotBlank(json)){
            return BeanUtil.toBean(json,type);
        }
        // 再对结果进行判断，如果不等于空，则一定是空字符串，同样结果返回空
        if (json != null){
            return null;
        }
        // 程序到此，则去查数据库查询
        R r = dbFallBack.apply(id);
        // 对查询出来的结果进行判断
        if (r == null){
            stringRedisTemplate.opsForValue().set(key,"",null_key_ttl,TimeUnit.MINUTES);
            return null;
        }
        // 查到值之后，将查询的值写入redis
        this.set(key,r,time,timeUnit);
        return r;
    }

    /*public <R,ID> R getWithLocalTime(){

    }*/
}
